#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QHostAddress>
#include <QHostInfo>
#include <QAbstractSocket>
#include <QSound>
#include <QNetworkInterface>
#include <QTest>
#include <QThread>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    bool flag = false;
    ui->setupUi(this);

    QString ip_address;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses(); // 获取所有ip
    for (int i = 0; i < ipAddressesList.size(); ++i)
    {

        QHostAddress ipAddr = ipAddressesList.at(i);
        if ((ipAddr.protocol() == QAbstractSocket::IPv4Protocol))// 筛选出ipv4
        {
            qDebug() << "----ipv4: " << ipAddr.toString();
            if(!ipAddr.toString().startsWith("127")){
                flag = true;
                ui->lineEdit_Port_2->setText(ipAddr.toString());
                break;
            }
        }
    }

    if(!flag){
        ui->lineEdit_Port_2->setText("127.0.0.1");
    }

    ui->lineEdit_Port->setText("8888");

    switchButtonStatus(false);

    server = new QTcpServer();

    //连接信号槽
    connect(server,&QTcpServer::newConnection,this,&MainWindow::server_New_Connect);

    timer1 = new QTimer(this);
    timer2 = new QTimer(this);
    timer3 = new QTimer(this);

    connect(timer1, SIGNAL(timeout()), this, SLOT(onTimer1TimeOut()));
    connect(timer2, SIGNAL(timeout()), this, SLOT(onTimer2TimeOut()));
    connect(timer3, SIGNAL(timeout()), this, SLOT(onTimer3TimeOut()));


    /* 自定义的录音类 */
    myAudioRecorder = new AudioRecorder(this);

    /* 自定义的百度云识别录音类 */
    myAsr = new Asr(this);

    /* 自定义的百度云人脸识别类 */
    myfacedection = new facedetection(this);

    connect(myfacedection, SIGNAL(faceRes(int, bool, QString)), this, SLOT(onFaceRes(int, bool, QString)));

    connect(this, SIGNAL(successFoundName(QString)), this, SLOT(onSuccessFoundName(QString)));

    /* LED */
    myLed = new Led(this);

    connect(myAsr, SIGNAL(asrReadyData(QString)), this, SLOT(onAsrReadyData(QString)));
}

MainWindow::~MainWindow()
{
    server->close();
    server->deleteLater();
    delete ui;
}

void MainWindow::showText(const QString &text){
    QString str = ui->textBrowser_Recv->toPlainText();
    str = str + text + tr("\n");
    //刷新显示
    ui->textBrowser_Recv->setText(str);
    ui->textBrowser_Recv->moveCursor(QTextCursor::End);
}

void MainWindow::switchButtonStatus(bool t){
    ui->LED_open_Button->setEnabled(t);
    ui->LED_open_Button_2->setEnabled(t);
    ui->add_face_Button->setEnabled(t);
    ui->add_face_Button_2->setEnabled(t);
    ui->del_face_Button->setEnabled(t);
    ui->del_face_Button_2->setEnabled(t);
    ui->open_door_Button->setEnabled(t);
    ui->open_door_Button_2->setEnabled(t);
    //ui->pushButton_Listen->setEnabled(t);
    //ui->pushButton_Listen_2->setEnabled(t);
    ui->show_list_Button->setEnabled(t);
    ui->show_list_Button_2->setEnabled(t);
    ui->voiceButton->setEnabled(t);
    ui->voiceButton_2->setEnabled(t);
}

void MainWindow::on_pushButton_Listen_clicked()
{
    if(ui->pushButton_Listen->text() == tr("开始监听"))
    {
        //从输入框获取端口号
        int port = ui->lineEdit_Port->text().toInt();

        //监听指定的端口
        if(!server->listen(QHostAddress::Any, port))
        {
            //若出错，则输出错误信息
            qDebug()<<server->errorString();
            return;
        }
        //修改按键文字
        ui->pushButton_Listen->setText("取消监听");
        qDebug()<< "Listen succeessfully!";
    }
    else
    {
        //如果正在连接
        if(socket->state() == QAbstractSocket::ConnectedState)
        {
            //关闭连接
            socket->disconnectFromHost();
        }
        //取消侦听
        server->close();
        //修改按键文字
        ui->pushButton_Listen->setText("开始监听");
        //发送按键失能
        switchButtonStatus(false);
    }

}

void MainWindow::server_New_Connect()
{
    //获取客户端连接
    socket = server->nextPendingConnection();
    //连接QTcpSocket的信号槽，以读取新数据
    QObject::connect(socket, &QTcpSocket::readyRead, this, &MainWindow::socket_Read_Data);
    QObject::connect(socket, &QTcpSocket::disconnected, this, &MainWindow::socket_Disconnected);
    //发送按键使能
    switchButtonStatus(true);

    QString str = ui->textBrowser_Recv->toPlainText();
    quint32 addr_origin = socket->peerAddress().toIPv4Address();
    QHostAddress addr_host = QHostAddress(addr_origin);

    str= str + tr("新连接的客户端IP地址：") + addr_host.toString() + tr("\n");
    //刷新显示
    ui->textBrowser_Recv->setText(str);
    qDebug() << "A Client connect!";
    //先开灯
    socket->write("LED_ON");
    socket->flush();
}

void MainWindow::socket_Read_Data()
{
    qDebug() << 'test';
    //读取缓冲区数据
    QByteArray buffer = socket->readAll();
    QImage image;

    if(!buffer.isEmpty()){
        imageArray.append(buffer);

    }
    unsigned char* p = (unsigned char*)buffer.data();
    int i = 0;
    bool flag = false;

    while(i < buffer.size()){
        qDebug() << p[i] << ",";
        if((p[i]==0XFF)&&(p[i+1]==0XD9)){
            flag = true;
            break;
        }
        i++;
    }
    if(flag){
        QImage image;
        image.loadFromData(imageArray, "JPEG");
        ui->lb_pic->setPixmap(QPixmap::fromImage(image));
        imageArray.clear();
        if(addFaceMode)
            myfacedection->addFace(image, curUserName);
        else
            myfacedection->searchFace(image);
    }

}

void MainWindow::socket_Disconnected()
{
    //发送按键失能
    switchButtonStatus(false);
    qDebug() << "Disconnected!";
    showText("关闭连接!");
}

void MainWindow::on_LED_open_Button_clicked()
{
    if(ui->LED_open_Button_2->text() == "开灯"){
        socket->write("LED_ON");
        socket->flush();
        showText("开灯!");
        //QSound::play(":/audio/led_on.wav");
        myLed->setLedState(true);
        ui->LED_open_Button_2->setText("关灯");
    }
    else{
        socket->write("LED_OFF");
        socket->flush();
        showText("关灯!");
        //QSound::play(":/audio/led_off.wav");
        myLed->setLedState(true);
        ui->LED_open_Button_2->setText("开灯");
    }
}

void MainWindow::on_LED_open_Button_2_clicked()
{
    on_LED_open_Button_clicked();
}


void MainWindow::on_voiceButton_clicked()
{
    //QSound::play(":/audio/siri2.wav");
    timer2->start(10);
    //ui->voiceButton_2->setText("正在听您说话");
}

void MainWindow::on_voiceButton_2_clicked()
{
    on_voiceButton_clicked();
}

void MainWindow::onTimer1TimeOut()
{
    /* 停止录音，8s钟的短语音 */
    myAudioRecorder->stopRecorder();
    ui->voiceButton_2->setText("正在识别您的语音");
    timer1->stop();
    //myMovie->stop();
    QString fileName = QCoreApplication::applicationDirPath() + "/16k.wav";
    myAsr->getTheResult(fileName);
    timer3->start(2000);
}

void MainWindow::onTimer2TimeOut()
{
    timer1->start(4000);
    ui->voiceButton_2->setText("正在听您说话");
    /* 开始录音 */
    myAudioRecorder->startRecorder();
    timer2->stop();
}

void MainWindow::onTimer3TimeOut()
{
    ui->voiceButton_2->setText("语音控制");
    timer3->stop();
}

void MainWindow::onAsrReadyData(QString str)
{
    if (str.contains("开灯")){
        /*
        socket->write("LED_ON");
        socket->flush();
        myLed->setLedState(true);
        ui->LED_open_Button_2->setText("关灯");*/
        on_LED_open_Button_clicked();
    }
    else if (str.contains("关灯")){
        on_LED_open_Button_clicked();
    }
    else if (str.contains("开门")){
        on_open_door_Button_clicked();
    }
    else if (str.contains("录入人脸")){
        int beg = str.indexOf("录入人脸");
        curUserName = str.mid(0, beg);
        addFaceMode = false;
        on_add_face_Button_clicked();
    }
    else if (str.contains("取消")){
        addFaceMode = true;
        on_add_face_Button_clicked();
    }
    else if(str.contains("用户列表")){
        on_show_list_Button_clicked();
    }
    else if(str.contains("灯状态")){
        socket->write("STATUS");
        socket->flush();
    }
    else if(str.contains("删除人脸")){
        int beg = str.indexOf("删除人脸");
        curUserName = str.mid(0, beg);
        on_del_face_Button_clicked();
    }

    showText("识别结果是:\n" + str);
    //textLabel->adjustSize();
}



void MainWindow::onFaceRes(int opt, bool res, QString res_info){
    if(opt == 1){
        if(res == 0) {
            showText("人脸录入成功!");
            socket->write("ADD_FACE_OK");
            socket->flush();
            addFaceMode = false;
            curUserName = "";
            ui->add_face_Button_2->setText("录入人脸");
            //QSound::play(":/audio/add_face.wav");
        }
        else {
            showText("人脸录入失败，原因：" + res_info);
            socket->write("ADD_FACE_FAILED");
            socket->flush();
        }
    }
    else if(opt == 2){
        if(res == 0) {
            qDebug() << res_info;
            QStringList list = res_info.split(",");
            if(list[1].toDouble() < 80){
                showText("该人脸在人脸库中的匹配度较低:" + list[1]);
            }
            else {
                showText("该人脸在人脸库中" + list[0] + "人脸的匹配度较高:" + list[1]);
                on_open_door_Button_clicked();
            }
        }
        else {
            showText("无法匹配，原因:" + res_info);
        }
    }
    else if(opt == 3){
        if(res == 0) {
            qDebug() << res_info;
            QStringList list = res_info.split(",");
            qDebug() << list;
            showText(QString("当前已经录入%1个用户的人脸：").arg(list.size()));
            for(QString user_id : list){
                showText(user_id);
            }
        }
        else {
            showText("查询失败，原因:" + res_info);
        }
    }
    else if(opt == 4){
        if(res == 0) {
            qDebug() << "查询单个用户:" << res_info;
            if(res_info == myfacedection->curUserName){
                emit(successFoundName(myfacedection->curUserId));
            }
        }
        else {
            showText("查询失败，原因:" + res_info);
        }
    }
    else if(opt == 5){
        if(res == 0) {
            showText("删除成功!");
            //QSound::play(":/audio/del_face.wav");
        }
        else {
            showText("删除失败，原因:" + res_info);
        }
    }
    else if(opt == 6){
        if(res == 0) {
            QStringList list = res_info.split(",");
            for(int i = 0; i < list.size(); i ++){
                myfacedection->getUserInfo(list[i]);
            }
        }
        else {
            showText("删除失败，原因:" + res_info);
        }
    }
}

void MainWindow::onSuccessFoundName(QString userId){
    myfacedection->delFace(userId);
}


void MainWindow::on_open_door_Button_clicked()
{

    socket->write("OPEN_DOOR");
    socket->flush();
    //QSound::play(":/audio/open_door.wav");
    showText("开门!");
}

void MainWindow::on_open_door_Button_2_clicked()
{
    on_open_door_Button_clicked();
}


void MainWindow::on_add_face_Button_clicked()
{
    /*
    QImage image("/home/zhuwenxi/face_detection/testset/jay.png");
    QString user_name = "jay";
    myfacedection->addFace(image, user_name);*/
    if(addFaceMode == false){
        addFaceMode = true;
        socket->write("ADD_FACE");
        socket->flush();
        ui->add_face_Button_2->setText("取消录入");
        showText("进入人脸录入模式");
    }
    else {
        addFaceMode = false;
        ui->add_face_Button_2->setText("录入人脸");
        showText("退出人脸录入模式");
    }

}

void MainWindow::on_show_list_Button_clicked()
{
    myfacedection->getUserList();
}

void MainWindow::on_show_list_Button_2_clicked()
{
    on_show_list_Button_clicked();
}

void MainWindow::on_del_face_Button_clicked()
{
    //myfacedection->delFaceByName(curUserName);
    myfacedection->delFace("1626865476");
    myfacedection->delFace("1626866037");
}

void MainWindow::on_del_face_Button_2_clicked()
{
    on_del_face_Button_clicked();
}
